package com.baselib.libnetwork.net.simpledown;

import android.text.TextUtils;

import com.baselib.libnetwork.net.HttpManager;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Date: 2018/5/19 14:41
 * Email: lixuce@letspie.com
 * Author: lixuce
 * Description:
 */
public class DownloadUtil {


    public static void download(String url, final String path, final DownloadCallback callback) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) {
            if (callback != null) {
                callback.onDownloadException(new Exception(TextUtils.isEmpty(url) ? "url is null" : "path is null"));
            }
            return;
        }
        okhttp3.OkHttpClient client = new okhttp3.OkHttpClient();
        okhttp3.Request request = new okhttp3.Request.Builder().url(url).build();
        okhttp3.Call call = client.newCall(request);

        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            okhttp3.Response response = call.execute();
            fis = response.body().byteStream();
            long total = response.body().contentLength();

            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            fos = new FileOutputStream(file);

            byte[] bytes = new byte[1024 * 5];
            int count;
            while ((count = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, count);
                if (callback != null) {
                    callback.onProgressChanged(file.length(), total);
                }
            }
            fis.close();
            fis = null;
            fos.flush();
            fos.close();
            fos = null;
            if (callback != null) {
                callback.onDownloadSuccess(file);
            }
        } catch (Exception e) {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e1) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e1) {
                }
            }
            if (callback != null) {
                callback.onDownloadException(e);
            }
        }
    }


    public static void downloadSong(String url, final String path, Object tag, final DownloadCallback callback) {
        if (TextUtils.isEmpty(url) || TextUtils.isEmpty(path)) {
            if (callback != null) {
                callback.onDownloadException(new Exception(TextUtils.isEmpty(url) ? "url is null" : "path is null"));
            }
            return;
        }

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().get().tag(tag).url(url).build();
        okhttp3.Call call = client.newCall(request);
        HttpManager.clientHashMap.put(tag, call);
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            okhttp3.Response response = call.execute();
            fis = response.body().byteStream();
            long total = response.body().contentLength();

            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            fos = new FileOutputStream(file);

            byte[] bytes = new byte[2048];
            int count;
            int sum=0;
          //  LogUtil.e("ZYZ---------total"+total);
            while ((count = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, count);
                sum+=count;
                if (callback != null) {
                    callback.onProgressChanged((long) (sum * 1.0f / total * 100), total);
                }
            }

            //  && total > 0 2.10.0 去掉该判断条件,部分文件该值为-1，影响下载（MediaPlayer直接create传网络uri会直接失败，提示文件不存在）
            if (sum >= total){
               // LogUtil.e("ZYZ---------sum"+sum);
                if (callback != null) {
                    callback.onDownloadSuccess(file);
                }
            }


            fis.close();
            fos.flush();
            fos.close();
            fis = null;
            fos = null;

        } catch (Exception e) {
           // LogUtil.e("ZYZ---------Exception");
            if (fis != null) {
                try {
                    fis.close();
                    fis = null;
                } catch (Exception e1) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (Exception e1) {
                }
            }
            if (callback != null) {
                callback.onDownloadFail();
            }
        } finally {
           // LogUtil.e("ZYZ---------finally");
            if (fis != null) {
                try {
                    fis.close();
                    fis = null;
                } catch (Exception e1) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (Exception e1) {
                }
            }
        }

    }

    public static void cancelByTag(Object tag) {
        if (tag == null) {
            return;
        }

        Call client = HttpManager.clientHashMap.get(tag);
        if (client == null) {
            return;
        }
        HttpManager.clientCancle.add(tag);
        client.cancel();
        HttpManager.clientHashMap.remove(tag);
    }
}
